<?php

class FP_Image_Scale extends FP_Image
{
    const HORIZONTAL = 'horizontal';
    const VERTICAL = 'vertical';

    public function __construct($pFile, $pMaxSize, $pScaleMode=self::HORIZONTAL, array $pOptions=array()){

	if (array_key_exists('cachedir', $pOptions)){
	    if (!array_key_exists('cacheid', $pOptions))
		throw new Exception('Missing cacheid parameter');

	    if ($this->validateCacheDir($pOptions['cachedir'])){

		$cachedfile = $pOptions['cachedir'] . "/fpscale-{$pOptions['cacheid']}-{$pMaxSize}-{$pScaleMode}.png";
		if (file_exists($cachedfile))
		    $this->create($cachedfile);
		else {
		    $this->process($pFile, $pMaxSize, $pScaleMode);
		    $this->save($cachedfile);
		}
	    } else
		$this->process($pFile, $pMaxSize, $pScaleMode);
	} else
	    $this->process($pFile, $pMaxSize, $pScaleMode);

	if (array_key_exists('destination', $pOptions))
	    $this->save($pOptions['destination']);
    }

    protected function process($pFile, $pMaxSize, $pScaleMode=self::HORIZONTAL){
	$img = $this->create($pFile);

	$owidth = $this->width;
	$oheight= $this->height;

	switch ($pScaleMode){
	case self::HORIZONTAL:
	$width = $pMaxSize;
	$height = round(($oheight * $width) / $owidth);
	break;
	case self::VERTICAL:
	$height = $pMaxSize;
	$width = round(($owidth * $height) / $oheight);
	default:
	throw new Exception('Unhandled scale mode '.$pScaleMode);
	}

	$this->image = ImageCreateTrueColor($width, $height);
	imagecopyresampled($this->image, $img, 0, 0, 0, 0, $width, $height, $owidth, $oheight);

	$this->width = $width;
	$this->height = $height;

	imagedestroy($img);

    }
}

?>